<?php

namespace App\Http\Controllers\Mobile;

use App\Models\Order;
use App\WeChat\WxPay\Order\WxPayUnifiedOrder;
use App\WeChat\WxPay\WxPayApi;
use Illuminate\Support\Facades\Auth;

class PayController extends BaseController
{
    //
    public function index()
    {

    }

    /**
     * @return \Illuminate\Http\JsonResponse
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function getsign()
    {

        $order_id = $this->request->input('order_id');
        $order = Order::find($order_id);

        if ($order) {
            $trade = $order->trade;
            $unifiedOrder = new WxPayUnifiedOrder();
            $unifiedOrder->setOutTradeNo($trade->out_trade_no);
            $unifiedOrder->setBody($trade->subject);
            $unifiedOrder->setDetail($trade->body);
            $unifiedOrder->setTotalFee($trade->total_amount*100);
            //$unifiedOrder->setTotalFee(2);
            $unifiedOrder->setNotifyUrl(url('weixin/notify'));
            $unifiedOrder->setTradeType('JSAPI');
            $unifiedOrder->setOpenid(Auth::user()->connect->openid);

            try {
                $response = WxPayApi::unifiedOrder($unifiedOrder);
                if ($response->tradeSuccess()) {
                    try {
                        return ajaxReturn($response->getJsApiContent());
                    }catch (\Exception $e) {
                        return ajaxError(1, $e->getMessage());
                    }
                } else {
                    return ajaxError($response->returnCode(), $response->retrunMsg());
                }
            } catch (\Exception $e){
                return ajaxError($e->getCode(), $e->getMessage());
            }

        } else {
            return ajaxError(404, 'order not found');
        }
    }

    public function success()
    {
        $order_id = $this->request->input('order_id');
        $order = Order::find($order_id);

        $this->assign(compact('order_id', 'order'));
        return $this->view('mobile.trade.pay_success');
    }
}
